<?php

class Video extends My_Controller
{

    var $data; // data array
    var $error = null;
    public function __construct()
    {
        parent::__construct("video");
        $this->load->model('video_model');
        $this->load->model('utility_model');
        $this->load->model('ngonngu_model');
        $this->load->model('quyen_model');
    }

    public function index()
    {
        // Build data
        $this->data['ngonngu'] = $this->ngonngu_model->dsNgonngu();

    }

    public function viewCreateVideo()
    {
        $this->authentication_model->checkAcess($this->quyen_model->getIdQuyen('them_video'));
        $this->data['dt'] = array('0' => array(
                'id' => '',
                'title' => '',
                'summary' => '',
                'content' => ''));
        $this->data['ngonngu'] = $this->ngonngu_model->dsNgonngu();

        if ($this->error != null)
            echo "<script>alert('" . $this->error . "')</script>";
        $this->template->parse_view('main_content', 'video/create.html', $this->data);
        $this->template->parse_view('info_content', 'template/info_content_create.html',
            $this->data);
        // Render template
        $this->template->render();
    }
    public function doCreateVideo()
    {
        $this->authentication_model->checkAcess($this->quyen_model->getIdQuyen('them_video'));
        $this->load->library('form_validation');
        $this->form_validation->set_rules('title', 'Tiêu đề video',
            'xss_clean|required|min_length[5]');
        $this->form_validation->set_rules('summary', 'Tóm tắt video',
            'xss_clean|required|min_length[5]|max_length[150]');
        //Dữ liệu cho phần dịch
            $content = $this->input->post('content');
            $id_mark = $this->input->post('id_mark');
            $id = $this->input->post('id');
            $image = $this->input->post('thumbnail');
            //Kết thúc dũ liệu phần dịch
        if ($this->form_validation->run())
        {
            $ngonngu = $this->security->xss_clean($this->input->post('ngonngu'));
            $chuyenmuc = $this->security->xss_clean($this->input->post('chuyenmuc'));
            $title = $this->security->xss_clean($this->input->post('title'));
            $summary = $this->security->xss_clean($this->input->post('summary'));
            $nguoitao = $this->session->userdata('userID');
            $tennguoitao = $this->session->userdata('user');
            $trangthai = $this->session->userdata('level');
            $checkExist=$this->utility_model->checkExist($title,'tieude_video','video');
            if($checkExist=="false_value") 
                {
                    $this->error="Tiêu đề đã tồn tại!";
                    $this->viewCreateVideo();
                    return;
                }
            else if($checkExist=="false_field")
                {
                    $this->error="Trường không tồn tại!";
                    $this->viewCreateVideo();
                    return;
                }
            //Xử lý upload anh
            if ($_FILES['imagefile']['name'] == false)
            {
                if ($id_mark == null)
                    $thumbnail = "no_photo.jpg";
                else
                    $thumbnail = $image;
            } else
            {
                if ($image_data = $this->utility_model->doUpload('image', 'imagefile', $this->
                    session->userdata('userID'), 'video'))
                {
                    $thumbnail = $image_data['duongdan'];
                } else
                {
                    $this->error = "Lỗi upload file ảnh!";
                    if ($id_mark == null)
                        $this->viewCreateVideo();
                    else
                        $this->viewEditVideo($id);
                }

            }
            //Xử lý upload video
            if ($_FILES['videofile']['name'] == false)
            {
                if ($id_mark == null)
                {
                    $this->error = "Bạn chưa chọn file video!";
                    $this->viewCreateVideo();
                } else
                    $noidung = $content;
            } else
            {
                if ($video_data = $this->utility_model->doUpload('video', 'videofile', $this->
                    session->userdata('userID'), 'video'))
                {
                    $noidung = $video_data['duongdan'];
                } else
                {
                    $this->error = "Lỗi upload file video!";
                    if ($id_mark == null)
                        $this->viewCreateVideo();
                    else
                        $this->viewEditVideo($id);
                }

            }
            if ($id_mark == null)
                $id_mark = $this->utility_model->random();
            if ($id_tao=$this->video_model->taovideo($id_mark, $ngonngu, $nguoitao, $tennguoitao, $title,
                $summary, $noidung, $chuyenmuc, $thumbnail, $trangthai))
            {
                $this->error = "Thêm video thành công!";
                if ($id == null)
                    $this->viewCreateVideo();
                else
                    $this->viewEditvideo($id_tao);
            } else
            {
                $this->error = "Lỗi thêm vào cơ sở dũ liệu!";
                if ($id_mark == null)
                    $this->viewCreateVideo();
                else
                    $this->viewEditVideo($id);
            }
        } else
        {
            if ($id_mark == null)
                $this->viewCreateVideo();
            else
                $this->viewEditVideo($id);
        }

    }
    public function viewEditVideo($id)
    {
        // Build data
        $this->authentication_model->checkAcess($this->quyen_model->getIdQuyen('sua_video'));
        if ($this->error != null)
            echo "<script>alert('" . $this->error . "')</script>";
        $this->data['ngonngu'] = $this->ngonngu_model->dsNgonngu();
        $result = $this->video_model->thongtinVideo($id);
        foreach ($result as $row)
            ;
        $this->data['id_mark'] = $row['id_mark'];
        $this->data['lang'] = $row['ngonngu'];
        $this->data['id_video'] = $row['id_video'];
        $this->data['chuyenmuc'] = $row['chuyenmuc'];
        $this->data['dt'] = array('0' => array(
                'id' => $row['id_video'],
                'title' => $row['tieude_video'],
                'summary' => $row['tomtat_video'],
                'thumbnail_video' => $row['thumbnail_video'],
                'content' => $row['noidung_video']));
        // Parser data
        $this->template->parse_view('main_content', 'video/edit.html', $this->data);
        $this->template->parse_view('info_content', 'video/info_content_edit.html', $this->data);
        // Render template
        $this->template->render();
    }
    public function doEditVideo()
    {
        $this->authentication_model->checkAcess($this->quyen_model->getIdQuyen('sua_video'));
        $this->load->library('form_validation');
        $id = $this->security->xss_clean($this->input->post('id'));
        $this->form_validation->set_rules('title', 'Tiêu đề video',
            'xss_clean|required|min_length[5]|max_length[150]');
        $this->form_validation->set_rules('summary', 'Tóm tắt video',
            'xss_clean|required|min_length[5]|max_length[150]');
        if ($this->form_validation->run())
        {
            $ngonngu = $this->security->xss_clean($this->input->post('ngonngu'));
            $chuyenmuc = $this->security->xss_clean($this->input->post('chuyenmuc'));
            $title = $this->security->xss_clean($this->input->post('title'));
            $summary = $this->security->xss_clean($this->input->post('summary'));
            $nguoitao = $this->session->userdata('userID');
            $tennguoitao = $this->session->userdata('user');
            $trangthai = $this->session->userdata('level');
            // Nếu file để trống thì lấy thumbnail cũ, nếu không thì upload mới
            if ($_FILES['imagefile']['name'] == false)
            {
                $thumbnail = $this->security->xss_clean($this->input->post('thumbnail'));
            } else
            {
                if ($image_data = $this->utility_model->doUpload('image', 'imagefile', $this->
                    session->userdata('userID'), 'video'))
                    $thumbnail = $image_data['duongdan'];
                else
                {
                    $this->error = "Lỗi upload file ảnh!";
                    $this->viewEditVideo($id);
                }
            }
            // Nếu video để trống thì lấy video cũ, nếu không thì upload mới
            if ($_FILES['videofile']['name'] == false)
            {
                $noidung = $this->security->xss_clean($this->input->post('content'));
            } else
            {
                if ($video_data = $this->utility_model->doUpload('video', 'videofile', $this->
                    session->userdata('userID'), 'video'))
                    $noidung = $video_data['duongdan'];
                else
                {
                    $this->error = "Lỗi upload file video!";
                    $this->viewEditVideo($id);
                }
            }
            //
            $id_mark = $this->utility_model->random();
            //Update vào cơ sở dữ liệu
            if ($this->video_model->suavideo($id, $nguoitao, $tennguoitao, $title, $summary,
                $noidung, $chuyenmuc, $thumbnail, $trangthai, $ngonngu))
                $this->viewEditVideo($id);
            else
            {
                $this->error = "Lỗi thêm vào cơ sở dũ liệu!";
                $this->viewViewVideo($id);
            }
        } // Kết thúc if form_validation->run()
        else
        {
            $this->viewEditVideo($id);
        }

    }
    public function doDeleteVideo($id)
    {
        $this->authentication_model->checkAcess($this->quyen_model->getIdQuyen('xoa_video'));
        if ($this->video_model->xoa($id))
        {
            echo "<script>alert('Xóa thành công!')</script>";
            $link = site_url("video/allfinal");
            $this->viewFinalVideos();
            //header("Location: $link");
        }

    }
    public function viewFinalVideos()
    {
        $this->data = array();
        $this->template->parse_view('main_content', 'video/table.html', $this->data);
        // Render template
        $this->template->render();
    }
    public function loadChuyenmuc($ngonngu, $chuyenmuc)
    {
        $this->load->model('chuyenmuc_model');
        $this->data = $this->chuyenmuc_model->laychuyenmucID($ngonngu);
        echo "<select name='chuyenmuc'>";
        foreach ($this->data as $row)
        {
            if ($chuyenmuc == $row['id_chuyenmuc'])
                $select = "selected='selected'";
            else
                $select = "";
            echo "<option value='" . $row['id_chuyenmuc'] . "'" . $select . ">" . $row['ten_chuyenmuc'] .
                "</option>";
        }
        echo "</select>";
    }
    public function getDataTable()
    {
        /* Indexed column (used for fast and accurate table cardinality) */
        $sIndexColumn = "ID";
        // DB table to use
        $sTable = 'video';

        $iDisplayStart = $this->input->get_post('iDisplayStart', true);
        $iDisplayLength = $this->input->get_post('iDisplayLength', true);
        $iSortCol_0 = $this->input->get_post('iSortCol_0', true);
        $iSortingCols = $this->input->get_post('iSortingCols', true);
        $sSearch = $this->input->get_post('sSearch', true);
        $sEcho = $this->input->get_post('sEcho', true);
        $_aColumns = array(
            'thumbnail_video',
            'tieude_video',
            'datetime_first',
            'datetime_last',
            'ten_nguoidung_first',
            'chuyenmuc',
            'trangthai_video',
            'ngonngu',
            'id_mark');
        // Paging
        if (isset($iDisplayStart) && $iDisplayLength != '-1' && $iDisplayLength != '0')
        {
            $this->db->limit($this->db->escape_str($iDisplayLength), $this->db->escape_str($iDisplayStart));
        }
        // Ordering
        if (isset($iSortCol_0))
        {
            for ($i = 0; $i < intval($iSortingCols); $i++)
            {
                $iSortCol = $this->input->get_post('iSortCol_' . $i, true);
                $bSortable = $this->input->get_post('bSortable_' . intval($iSortCol), true);
                $sSortDir = $this->input->get_post('sSortDir_' . $i, true);

                if ($bSortable == 'true')
                {
                    $this->db->order_by($_aColumns[intval($this->db->escape_str($iSortCol))], $this->
                        db->escape_str($sSortDir));
                }
            }
        }
        if (isset($sSearch) && !empty($sSearch))
        {
            for ($i = 0; $i < count($_aColumns); $i++)
            {
                $bSearchable = $this->input->get_post('bSearchable_' . $i, true);

                // Individual column filtering
                if (isset($bSearchable) && $bSearchable == 'true')
                {
                    $this->db->or_like($_aColumns[$i], $this->db->escape_like_str($sSearch));
                }
            }
        }
        // Select Data
        $this->db->select('id_video,thumbnail_video,tieude_video,datetime_first,datetime_last,ten_nguoidung_first,chuyenmuc.ten_chuyenmuc,trangthai_video,ngonngu.ngonngu as lang,video.id_mark');
        $this->db->from('video');
	    $this->db->join('ngonngu','ngonngu.id_ngonngu = video.ngonngu');
	    $this->db->join('chuyenmuc','chuyenmuc.id_chuyenmuc = video.chuyenmuc');
        $rResult = $this->db->get();
        $this->db->select('FOUND_ROWS() AS found_rows');
        $iFilteredTotal = $this->db->get()->row()->found_rows;
        // Total data set length
        $iTotal = $this->db->count_all($sTable);
        // Output
        $output = array(
            'sEcho' => intval($sEcho),
            'iTotalRecords' => $iTotal,
            'iTotalDisplayRecords' => $iFilteredTotal,
            'aaData' => array());
        $this->load->model('chuyenmuc_model');
        foreach ($rResult->result_array() as $hang)
        {
            $row = array();
            $id = $hang['id_video'];
            $linkSua = site_url("video/viewEditVideo/$id");
            $linkXoa = site_url("video/doDeleteVideo/$id");
            $confirm = "submitLink()";
            $sua = "<a href=$linkSua>Sửa</a>";
            $xoa = "<a href=$linkXoa onclick='return $confirm'>Xóa</a>";
            $row[] = "<img width='55'src=" . base_url($hang['thumbnail_video']) . "></img>";
            $row[] = $hang['tieude_video'];
            $row[] = $hang['datetime_first'];
            $row[] = $hang['datetime_last'];
            $row[] = $hang['ten_nguoidung_first'];
            $row[] = $hang['ten_chuyenmuc'];
            if ($hang['trangthai_video'] == 1)
                $row[] = "Đã duyệt";
            else
                $row[] = "Chưa duyệt";
            $row[]=$hang['lang'];
            $row[] = $sua;
            $row[] = $xoa;
            $output['aaData'][] = $row;
        }
        //echo "<pre>";
        //print_r($output);
        //echo "</pre>";
        echo json_encode($output);
    }

}
